package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.StationMapper;
import com.dwxt.cdms.entity.Role;
import com.dwxt.cdms.entity.Station;
import com.dwxt.cdms.entity.StationExample;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StationService {

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private UserServiceAdmin userServiceAdmin;

    public BaseResult page(Page page,String name) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        StationExample example = new StationExample();
        if (StringUtil.isNotBlank(name)) {
            example.createCriteria().andNameLike("%" + name + "%");
        }
        example.setOrderByClause("create_time desc");
        List<Station> stationList = stationMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(stationList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult list() {
        Integer loginUserStation = getLoginUserStation();
        StationExample example = new StationExample();
        if (loginUserStation != null) {
            example.createCriteria().andIdEqualTo(loginUserStation);
        }
        example.setOrderByClause("create_time desc");
        List<Station> stationList = stationMapper.selectByExample(example);
        return BaseResult.ok(stationList);
    }

    public BaseResult add(Station station) {
        stationMapper.insertSelective(station);
        return BaseResult.ok();
    }

    public BaseResult delete(Integer id) {
        stationMapper.deleteByPrimaryKey(id);
        return BaseResult.ok();
    }

    public BaseResult update(Station id) {
        stationMapper.updateByPrimaryKeySelective(id);
        return BaseResult.ok();
    }

    public Integer getLoginUserStation() {
        String userId = PartyUtil.getCurrentUserId();
        List<Role> roles = userServiceAdmin.selectRolesByUserId(userId);
        boolean b = roles.stream().anyMatch(role -> 1 == role.getId());
        Integer stationId=null;
        if (!b) {
            String stationIdStr = userServiceAdmin.selectUserById(Integer.valueOf(userId)).getStationId();
            if (StringUtils.isNotBlank(stationIdStr)) {
                String[] split = stationIdStr.split(",");
                stationId = Integer.valueOf(split[0]);
            }
        }
        return stationId;
    }

    public Station getStationById(Integer id) {
        return stationMapper.selectByPrimaryKey(id);
    }
}
